package cn.codewen.service.impl;

import cn.codewen.service.CosService;
import cn.codewen.utils.CosUtils;
import com.qcloud.cos.model.COSObjectSummary;
import com.qcloud.cos.model.PutObjectResult;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class CosServiceImpl implements CosService {
    @Override
    public List listObjects(String prefix) {

        CosUtils cosUtils = new CosUtils();
        List<COSObjectSummary> listObjects = cosUtils.listObjects(prefix);

        ArrayList<COSObjectSummary> dirs = new ArrayList<>();
        ArrayList<COSObjectSummary> files = new ArrayList<>();
        for (COSObjectSummary listObject : listObjects) {

            //去除前缀prefix
            String newDir = listObject.getKey().replace(prefix, "");
            System.out.println(newDir);
            // 用 计算出现 / 的次数
            int count = newDir.length() - newDir.replace("/", "").length();


            if (listObject.getSize() == 0 && count == 1) {
                dirs.add(listObject);
            }
            if (listObject.getSize() > 0 && count == 0) {
                files.add(listObject);
            }
        }
        dirs.addAll(files);
        return dirs;
    }

    @Override
    public Boolean addDirs(String key) {

        //1 创建工具类对象
        CosUtils cosUtils = new CosUtils();
        //2 调用方法
        String rs = cosUtils.addDirs(key);
        if (rs!=null){
            return true;
        }else {
            return false;
        }


    }

    @Override
    public Boolean addFile(String localFilePath, String key) {
        //1 创建工具类对象
        CosUtils cosUtils = new CosUtils();
        //2 调用方法
        PutObjectResult rs = cosUtils.addFile(localFilePath, key);
        if (rs!=null){
            return true;
        }else {
            return false;
        }
    }
}
